import {Injectable} from '@angular/core';

@Injectable()
export class StorageService {
  currData: string;
  session: any;
  local: any;
  constructor() {
    if ( !sessionStorage ) {
      throw new Error('Current browser does not support Session Storage');
    }
    if ( !localStorage ) {
      throw new Error('Current browser does not support Local Storage');
    }
    this.session = sessionStorage;
    this.local = localStorage;
    this.currData = 'local';
  }

  public set(key: string, value: string): void {
    this[this.currData][key] = value;
  }

  public get(key: string) {
    return this[this.currData][key] || false;
  }

  public has(key: string): boolean {
    const keyItem = this[this.currData][key];
    return keyItem != null ? true : false;
  }

  public setObject(key: string, value: any) {
    this[this.currData][key] = JSON.stringify(value);
    return this;
  }

  public getObject(key: string) {
    return JSON.parse(this[this.currData][key] || '{}');
  }

  public remove(key: string): any {
    this[this.currData].removeItem(key);
  }
  public set modules(data: any){
    this.setObject(SKey[SKey.ModuleData], data);
  }
  public get modules(){
    return this.getObject(SKey[SKey.ModuleData]);
  }
  public set dictionary(data: any){
    this.setObject(SKey[SKey.DicData], data);
  }
  public get dictionary(){
    return this.getObject(SKey[SKey.DicData]);
  }
  public set user(data: any){
    this.setObject(SKey[SKey.UserData], data);
  }
  public get user(){
    return this.getObject(SKey[SKey.UserData]);
  }
  public set token(data: any){
    this.setObject(SKey[SKey.TokenData], data);
  }
  public get token(){
    return this.getObject(SKey[SKey.TokenData]);
  }
  public set menuCurr(data: any){
    this.setObject(SKey[SKey.CurrentModuleData], data);
  }
  public get menuCurr(){
    return this.getObject(SKey[SKey.CurrentModuleData]);
  }
  public clear() {
    this[this.currData].clear();
  }
}
export enum SKey {
  ModuleData,
  DicData,
  UserData,
  TokenData,
  CurrentModuleData
}
